package com.example.benefitcommunity.interceptor;

import com.example.benefitcommunity.util.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Nonnull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.HashMap;
import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(JWTInterceptor.class);

    /**
     * 通过用户和密码查询
     *
     * @param request  请求
     * @param response 响应
     *                 //     * @param handler  处理
     * @return 单条数据
     */
    @Override
    public boolean preHandle( @Nonnull HttpServletRequest request,
                              @Nonnull HttpServletResponse response,
                              @Nonnull Object handle) throws Exception {
        //对options请求进行处理
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 创建一个Map对象，用于存储响应信息
        Map<String, Object> map = new HashMap<>(30);
        // 从请求头中获取令牌
        String token = request.getHeader("token");

        try {
            // 验证令牌的有效性
            Claims claims = JWTUtil.checkJWT(token);
            if (claims != null) {
                //放行请求
                return true;
            }
        } catch (Exception e) {
            logger.error("JWT验证失败", e); // 使用日志记录异常
            map.put("msg", "验证失败:" + e);
        }
        //设置状态为false,状态码为401
        map.put("code", 401);
        map.put("data", null);
        //将Map转化为JSON字符串（使用Jackson库）
        String json = new ObjectMapper().writeValueAsString(map);
        //设置响应的Content-Type
        response.setContentType("application/json;charset=UTF-8");
        //将JSON字符串写入响应中
        response.getWriter().println(json);
        //不放行请求
        return false;
    }
}
